// 高德地图API接口
import request from './request.js';
// 高德地图天气API key:34fa990705567fbd36fe552ce882fc7a
const API_KEY = '34fa990705567fbd36fe552ce882fc7a';

// 获取天气信息
export const getWeather = (city) => {
  return request.get(`weather/weatherInfo?key=${API_KEY}&city=${encodeURIComponent(city)}&extensions=all&output=JSON`);
};

// 地理编码接口
export const getLocation = (address) => {
  return request.get(`geocode/geo?key=${API_KEY}&address=${encodeURIComponent(address)}&output=JSON`);
};

// 搜索地址
export function searchAddress({ keywords, city, offset = 20, page = 1, extensions = 'all' }) {
  return request({
    url: '/place/text',
    method: 'get',
    params: {
      keywords,
      city,
      offset,
      page,
      extensions,
      key: API_KEY
    }
  }).then(response => {
    // 在搜索地址后同时获取天气信息和位置信息
    if (response.status === '1' && response.geocodes?.length) {
      const geoData = response.geocodes[0];
      
      // 获取天气信息
      return getWeather(geoData.city || geoData.district || geoData.province)
        .then(weatherResponse => {
          return {
            address: response,
            weather: weatherResponse,
            location: geoData
          };
        })
        .catch(error => {
          console.error('获取天气信息失败:', error);
          return {
            address: response,
            weather: null,
            location: geoData,
            addressError: null,
            weatherError: error
          };
        });
    } else {
      throw new Error('未找到相关的地址信息');
    }
  });
};